package com.example.hidesms;

import java.util.ArrayList;
import java.util.Stack;

import android.os.Bundle;
import android.os.Handler;
import android.os.Parcel;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.util.Log;
import android.view.Menu;
import android.view.View;
import android.widget.FrameLayout;

import com.example.hidesms.HomePageFragment.HomeListener;
import com.example.hidesms.dto.SMSItem;
import com.example.hidesms.utils.ApplicationDatas;
import com.example.hidesms.utils.Utils;
import com.slidingmenu.lib.SlidingMenu;
import com.slidingmenu.lib.app.SlidingFragmentActivity;

public class HideSMSActivity extends SlidingFragmentActivity implements HomeListener {
	public final static String	TAG							= HideSMSActivity.class.getSimpleName();
	private String				currentKey					= TAG;
	private String				currentKeyFilter			= TAG + "filter";
	private String				currentKeyGenres			= TAG + "genres";
	private String				currentId					= "-1";
	// private PubRetainFragment retainFragment;

	public final int			ID_HOMEPAGE_LAYOUT			= R.id.homepageFragment;
	public final int			ID_CATEGORY_LAYOUT			= R.id.categoryFragment;
	public final int			ID_DETAIL_LAYOUT			= R.id.detailFragment;
	public final int			ID_OVER_LAYOUT				= R.id.overlayFragment;
	// View
	private FrameLayout			overlayLayout				= null;
	private FrameLayout			homepageLayout				= null;
	private FrameLayout			categoryLayout				= null;
	private FrameLayout			detailLayout				= null;
	private Fragment			currentBackStackFragment	= null;
	private Fragment			currentOverlayFragment		= null;
	private CategoryFragment			currentCateFragment		= null;
	private Stack<String>		screenTags					= new Stack<String>();
	private Handler				handler						= new Handler();
	
	
	private String currentCateAddress;

	// private Preference mPreference;

	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.activity_main);
		initView();
		setBehindContentView(R.layout.frame);
		FragmentTransaction t = getSupportFragmentManager().beginTransaction();
		t.add(R.id.frame, MenuFacebookFragment.newInstance(new MenuFacebookRetain(this)));
		// t.addToBackStack(null);
		t.commit();
		// customize the SlidingMenu
		setSlidingActionBarEnabled(true);
		getSlidingMenu().setTouchModeAbove(SlidingMenu.TOUCHMODE_FULLSCREEN);
		getSlidingMenu().setShadowWidthRes(R.dimen.shadow_width);
		getSlidingMenu().setShadowDrawable(R.drawable.shadow);
		getSlidingMenu().setBehindOffsetRes(R.dimen.actionbar_home_width);

		getSlidingMenu().setBehindScrollScale(0.25f);
//		getSMS();
		HomePageFragment homePageFragment = new HomePageFragment();
		homePageFragment.setHomeListener(this);
		addFragment(homePageFragment, ApplicationDatas.HOMEPAGE_SCREEN_TAG, null);
	}

	@Override
	public boolean onCreateOptionsMenu(Menu menu) {
		// Inflate the menu; this adds items to the action bar if it is present.
		getMenuInflater().inflate(R.menu.main, menu);
		return true;
	}

	private void visibleAllView(String tag) {
		if (tag.equals(ApplicationDatas.HOMEPAGE_SCREEN_TAG)) {
			homepageLayout.setVisibility(View.VISIBLE);
			categoryLayout.setVisibility(View.GONE);
			detailLayout.setVisibility(View.GONE);
		} else if (tag.equals(ApplicationDatas.LIST_SCREEN_TAG)) {
			homepageLayout.setVisibility(View.VISIBLE);
			categoryLayout.setVisibility(View.VISIBLE);
			detailLayout.setVisibility(View.GONE);
		} else if (tag.equals(ApplicationDatas.DETAIL_SCREEN_TAG)) {
			homepageLayout.setVisibility(View.GONE);
			categoryLayout.setVisibility(View.VISIBLE);
			detailLayout.setVisibility(View.VISIBLE);
		}
	}
	private void initView() {
//		if (mPreference == null) {
//			mPreference = new Preference(this);
//		}
		if (overlayLayout == null) {
			overlayLayout = (FrameLayout) findViewById(ID_OVER_LAYOUT);
		}
		if (homepageLayout == null) {
			homepageLayout = (FrameLayout) findViewById(ID_HOMEPAGE_LAYOUT);
		}
		if (categoryLayout == null) {
			categoryLayout = (FrameLayout) findViewById(ID_CATEGORY_LAYOUT);
		}
		if (detailLayout == null) {
			detailLayout = (FrameLayout) findViewById(ID_DETAIL_LAYOUT);
			// detailLayout.setOnClickListener(null);
		}
	}

	private void addFragment(Fragment fragment, String tag, Object object) {
		if (fragment == null && Utils.isNull(tag))
			throw new NullPointerException("Null point Exception : fragment or tag is null");
		Fragment flipFragmentExist = (Fragment) getSupportFragmentManager().findFragmentByTag(tag);
		FragmentTransaction frt = getSupportFragmentManager().beginTransaction();
		Log.e("add tagq", "add tag " + tag);
		if (flipFragmentExist != null) {
			if (fragment.isAdded() && fragment.equals(flipFragmentExist)) {
				Log.e("show", "bang");

			} else {
				Log.e("show", "kobang");
				// if (fragment instanceof ListFilmThreeTypeFragmentTabhost) {
				// ((ListFilmThreeTypeFragmentTabhost)
				// flipFragmentExist).setType((String) object);
				// }
			}
			currentBackStackFragment = flipFragmentExist;
			frt.show(flipFragmentExist);
		} else {
			int fragmentId;
			if (tag.equals(ApplicationDatas.HOMEPAGE_SCREEN_TAG)) {
				fragmentId = ID_HOMEPAGE_LAYOUT;
			} else if (tag.equals(ApplicationDatas.CATEGORY_SCREEN_TAG)
					|| tag.equals(ApplicationDatas.CATEGORY_COOL_TAG)) {
				fragmentId = ID_CATEGORY_LAYOUT;
			} else if (tag.equals(ApplicationDatas.DETAIL_SCREEN_TAG)) {
				fragmentId = ID_DETAIL_LAYOUT;
			} else {
				fragmentId = -1;
			}

			if (fragmentId == -1)
				throw new NullPointerException("Not found Exception : tag not found");
			if (fragment instanceof HomePageFragment) {
				Log.e("add", "add");
				frt.add(fragmentId, fragment, tag);
			} else {
				Log.e("replace", "replace");
				frt.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_OPEN);
				frt.replace(fragmentId, fragment, tag);
			}
			currentBackStackFragment = fragment;

		}
		frt.commit();
		if (tag.equals(ApplicationDatas.HOMEPAGE_SCREEN_TAG)) {
			homepageLayout.setVisibility(View.VISIBLE);
		} else if (tag.equals(ApplicationDatas.CATEGORY_SCREEN_TAG)
				|| tag.equals(ApplicationDatas.CATEGORY_COOL_TAG)) {
			categoryLayout.setVisibility(View.VISIBLE);
		} else if (tag.equals(ApplicationDatas.DETAIL_SCREEN_TAG)) {
			detailLayout.setVisibility(View.VISIBLE);
		}
		Log.e("sdfsdf", "asdfsd " + screenTags);
		if (screenTags != null && !screenTags.isEmpty()) {
			if (!screenTags.lastElement().equals(tag))
				screenTags.push(tag);
		} else {
			screenTags.push(tag);
		}
	}

	public void removeFragmentBackStack(final String tag) {
		if (Utils.isNull(tag))
			throw new NullPointerException("Null point Exception : fragment or tag is null");
		Fragment removeFragment = (Fragment) getSupportFragmentManager().findFragmentByTag(tag);
		if (removeFragment != null && removeFragment.isAdded()) {
			if (screenTags != null && !screenTags.isEmpty() && screenTags.indexOf(tag) >= 0) {
				screenTags.pop();
				if (screenTags.isEmpty()) {
					FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
					if (overlayLayout != null) {
						overlayLayout.setVisibility(View.VISIBLE);
						overlayLayout.removeAllViews();
						overlayLayout = null;
					}
					if (currentOverlayFragment != null) {
						fragmentTransaction.remove(currentOverlayFragment);
						currentOverlayFragment = null;
					}
					fragmentTransaction.remove(removeFragment);
					currentBackStackFragment = null;
					fragmentTransaction.commit();
					finish();
					return;
				}
				final String currentTag = screenTags.lastElement();
				FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
				fragmentTransaction.hide(removeFragment);
				fragmentTransaction.commit();
				handler.postDelayed(new Runnable() {
					@Override
					public void run() {
						visibleAllView(currentTag);
						Fragment preFragment = (Fragment) getSupportFragmentManager().findFragmentByTag(currentTag);
						if (preFragment != null) {
							currentBackStackFragment = preFragment;
						}
					}
				}, 200);
			}
		}
	}

	public void addFragmentOverlayLayout(Fragment overLayFragment, String tag) {
		if (overLayFragment == null)
			throw new NullPointerException("FlipFragment must not null");
		FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
		fragmentTransaction.replace(ID_OVER_LAYOUT, overLayFragment, tag);
		fragmentTransaction.commit();
		overlayLayout.setVisibility(View.VISIBLE);
		currentOverlayFragment = overLayFragment;

		if (!screenTags.lastElement().equals(tag))
			screenTags.push(tag);
	}

	public void removeFragmentOverlayLayout(int animationIn, int animationOut, String tag) {
		if (currentOverlayFragment != null) {
			FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();
			fragmentTransaction.remove(currentOverlayFragment);
			fragmentTransaction.commit();
			currentOverlayFragment = null;

			handler.postDelayed(new Runnable() {
				@Override
				public void run() {
					if (overlayLayout != null) {
						overlayLayout.removeAllViews();
						overlayLayout.setVisibility(View.GONE);
					}
				}
			}, 200);
			if (screenTags != null && !screenTags.isEmpty())
				screenTags.remove(tag);
		}
	}
	@Override
	public void onBackPressed() {
		if (screenTags != null && !screenTags.isEmpty()) {
			String currentTag = screenTags.lastElement();
			for (int i = 0; i < screenTags.size(); i++) {
				Log.e("scren", "scren " + screenTags.get(i));

			}
			if (currentOverlayFragment != null) {
				removeFragmentOverlayLayout(-1, -1, currentTag);
			} else {
				Log.e("onac else", "onac else " + currentTag);
				Log.e("currentOverlayFragment", "currentOverlayFragment " + currentOverlayFragment);
				Log.e("currentBackStackFragment", "currentBackStackFragment " + currentBackStackFragment);
				if (!Utils.isEmpty(currentTag)) {
					removeFragmentBackStack(currentTag);
				} else {
					super.onBackPressed();
				}
			}
		} else {
			super.onBackPressed();
		}
	}

	private void getSMS() {
		// Uri mSmsQueryUri = Uri.parse("content://sms");
		// ContentResolver content = getContentResolver();
		// //String selection = "0==0) GROUP BY (" + "thread_id";
		// Cursor cursor = content.query(mSmsQueryUri, null, null, null, null);
		// // SMSadap = new CustomSMSAdapter(this, cursor, content);
		// cursor.moveToFirst();
		//
		// do{
		// String msgData = "";
		// for(int idx=0;idx<cursor.getColumnCount();idx++)
		// {
		// msgData += " " + cursor.getColumnName(idx) + ":" +
		// cursor.getString(idx);
		// }
		// Log.e("getSMS", " "+msgData);
		// }while(cursor.moveToNext());
		ArrayList<SMSItem> lstSMS = Utils.getAllSms(this);
		String msgData = "";
		for (int i = 0; i < lstSMS.size(); i++) {
			msgData += "Content: " + lstSMS.get(i).getMsg();
		}
		Log.e("getSMS", " " + msgData);
	}

	@Override
	public void startCate(String address) {
		if (currentCateFragment!=null) {
			if (currentCateAddress.equals(address)) {
				
			}else{
				currentCateFragment.setAddress(address);
				currentCateAddress =address;
			}
		}else{
			currentCateFragment = CategoryFragment.instance(address);
			currentCateAddress = address;
		}
		
		addFragment(currentCateFragment, ApplicationDatas.CATEGORY_SCREEN_TAG, null);
	}

	@Override
	public void addListBlock() {
		addFragmentOverlayLayout(ListBlockSms.instance(), ApplicationDatas.BLOCK_SCREEN_TAG);
		showAbove();
	}

	@Override
	public int describeContents() {
		// TODO Auto-generated method stub
		return 0;
	}

	@Override
	public void writeToParcel(Parcel dest, int flags) {
		// TODO Auto-generated method stub
		
	}

	@Override
	public void addListBlockIncoming() {
		// TODO Auto-generated method stub
		addFragmentOverlayLayout(ListBlockInComing.instance(), ApplicationDatas.BLOCK_SCREEN_TAG);
		showAbove();
	}

	@Override
	public void addListBlockOutgoing() {
		// TODO Auto-generated method stub
		addFragmentOverlayLayout(ListBlockOutGoing.instance(), ApplicationDatas.BLOCK_SCREEN_TAG);
		showAbove();
	}

	@Override
	public void addListCoolSms() {
		// TODO Auto-generated method stub
		addFragment(ListCoolSMS.instance(), ApplicationDatas.CATEGORY_COOL_TAG, null);
		showAbove();
	}

}
